//
//  YHStatusListViewModel.swift
//  YHWeibo
//
//  Created by 昱含 on 16/5/25.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit

class YHStatusListViewModel: NSObject {
    
//    lazy var statuses: [YHStatus] = [YHStatus]()
    lazy var statusViewModelArray: [YHStatusViewModel] = [YHStatusViewModel]()
    
    func loadHomeData(isPulling: Bool, finished: (isSuccess:Bool,count: Int) -> ()) {
        
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        if isPulling {
            
            max_id = statusViewModelArray.last?.status?.id ?? 0
            
        }else{
            
            since_id = statusViewModelArray.first?.status?.id ?? 0
            
        }
    
        YHNetworkTools.sharedTools.loadHomePageData(since_id, max_id: max_id) { (responseObject, error) in
            if error != nil {

                finished(isSuccess: false,count: 0)
                return
            }
            //                        print(responseObject)
            guard let dict = responseObject as? [String : AnyObject] else{
                
                //            print(dict)
                finished(isSuccess: false,count: 0)
                return
            }
            
            //实际拿到的是AnyObject类型,还是需要类型转换
            guard let array = dict["statuses"] as? [[String : AnyObject]] else{
                
                finished(isSuccess: false,count: 0)
                
                return
            }
            
            var temArray = [YHStatusViewModel]()
            
            for item in array {
                
                let s = YHStatus(dict: item)
                //在数组中添加视图模型
                let viewModel = YHStatusViewModel(status: s)
                temArray.append(viewModel)
                
//                print(temArray.count)

            }
            
//            if since_id > 0 {
//            
//                self.statusViewModelArray = temArray + self.statusViewModelArray
//            }
            //    self.statusViewModelArray = temArray
            
            if isPulling{
                
                self.statusViewModelArray = self.statusViewModelArray + temArray
            } else {
                //刷新新数据
                self.statusViewModelArray = temArray + self.statusViewModelArray
            }

                finished(isSuccess: true,count: temArray.count)
                //                self.tableView.reloadData()
                
            }
            
        }

    }
            

